package com.infore.exchange.main.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.infore.common.base.EppPage;
import com.infore.common.base.Msg;
import com.infore.common.base.ResultUtil;
import com.infore.common.base.WrapperHelp;
import com.infore.common.fw.BaseController;
import com.infore.common.model.entity.exchange.TDatabaseInfo;
import com.infore.common.model.entity.vo.exchange.TDatabaseInfoVo;
import com.infore.common.request.addupdate.exchange.TDatabaseInfoSaveRequest;
import com.infore.common.response.ApiListResponse;
import com.infore.common.response.ApiResponse;
import com.infore.common.utils.StringUtils;
import com.infore.common.utils.UUIDGenerator;
import com.infore.exchange.main.service.TDatabaseInfoService;
import com.infore.metadata.core.model.TableModel;
import com.infore.screw.core.metadata.Table;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 数据库信息表 前端控制器
 * </p>
 *
 * @author lijh
 * @since 2023-02-07
 */
@RestController
@Api(value = "数据库信息表前端控制器", tags = "数据库信息表前端控制器")
@RequestMapping("/tDatabaseInfo")
public class TDatabaseInfoController extends BaseController {
	private String prefix = "/tDatabaseInfo";

	@Autowired
	private TDatabaseInfoService TDatabaseInfoService;

	@GetMapping()
	public String TDatabaseInfoController(){
		return prefix;
	}

	/**
	 * 查询数据库信息表列表
	 * @param tdatabaseinfoVo 数据库信息表的vo类
	 * @return Msg<Object> 结果集
	 * @author lijh
	 * @since 2023-02-07
	 */
	@PostMapping("/list")
	@ResponseBody
	@ApiOperation(value = "查询数据库信息表列表", notes = "数据库信息表列表查询 ")
	public Msg<Object> list(TDatabaseInfoVo tdatabaseinfoVo){
		//sql查询条件
		Wrapper<TDatabaseInfo> wrapper = null ;
		try {
			wrapper = (Wrapper<TDatabaseInfo>) WrapperHelp.addCondition(new EntityWrapper<TDatabaseInfo>(), tdatabaseinfoVo);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.error(500,e.getMessage());
		}
		//查询方法
		Page<TDatabaseInfo> eppPage = new EppPage<TDatabaseInfo>(TDatabaseInfoService,tdatabaseinfoVo,wrapper);
		return ResultUtil.successPage(TDatabaseInfoService.selectPage(eppPage, wrapper));
	}



	@PostMapping("/query")
	@ResponseBody
	@ApiOperation(value = "查询数据库信息表列表-不分页", notes = "数据库信息表列表查询-不分页 ")
	public Msg<Object> query(TDatabaseInfoVo tdatabaseinfoVo){
		//sql查询条件
		Wrapper<TDatabaseInfo> wrapper = null ;
		try {
			wrapper = (Wrapper<TDatabaseInfo>) WrapperHelp.addCondition(new EntityWrapper<TDatabaseInfo>(), tdatabaseinfoVo);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.error(500,e.getMessage());
		}
        List<TDatabaseInfo> tDatabaseInfos = TDatabaseInfoService.selectList(wrapper);
		return ResultUtil.successData(tDatabaseInfos);
	}
	/**
	 * 删除数据库信息表
	 *
	 * @param  databaseId
	 * @return Msg<Object>
	 * @author lijh
	 * @since 2023-02-07
	 */
	@RequestMapping(value = "/del", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "删除数据库信息表", notes = "删除数据库信息表")
	public Msg<Object> del(String databaseId) {

		Map<String, Object> columnMap = new HashMap<String, Object>();
		columnMap.put("database_id", databaseId);
		boolean flag = TDatabaseInfoService.deleteByMap(columnMap);
		return ResultUtil.setResult(flag);
	}


	@ResponseBody
	@ApiOperation(value = "新增或编辑数据库信息表", notes = "新增或编辑数据库信息表")
	@RequestMapping(value = "/addOrEdit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public Msg<Object> addOrEdit(@RequestBody TDatabaseInfo tdatabaseinfo) {
		boolean flag = false;
		if(StringUtils.isEmpty(tdatabaseinfo.getDatabaseId()) ){
			//新增
			Wrapper<TDatabaseInfo> wrapper = new  EntityWrapper<TDatabaseInfo>();
			wrapper.eq("database_name", tdatabaseinfo.getDatabaseName());
			List<TDatabaseInfo> entityList = TDatabaseInfoService.selectList(wrapper);
			if(entityList.size()>0) {
				return ResultUtil.error("业务库已存在");
			}
			tdatabaseinfo.setDatabaseId(UUIDGenerator.generator());
			tdatabaseinfo.setCreateTime(new Date());
            tdatabaseinfo.setUpdateTime(new Date());
			TDatabaseInfoService.checkDatabaseConnect(tdatabaseinfo);
			//插入数据
			flag = TDatabaseInfoService.insert(tdatabaseinfo);

		}else{
			TDatabaseInfoService.checkDatabaseConnect(tdatabaseinfo);
			tdatabaseinfo.setUpdateTime(new Date());
			flag = TDatabaseInfoService.updateById(tdatabaseinfo);
		}
		return ResultUtil.setResult(flag, tdatabaseinfo.getDatabaseId());
	}

	@RequestMapping(value = "/checkDatabaseConnect", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@ApiOperation(value = "校验数据源连接", notes = "校验数据源连接")
	public ApiResponse checkDatabaseConnect(@ModelAttribute TDatabaseInfoSaveRequest request) {
		TDatabaseInfo entity = new TDatabaseInfo();
		BeanUtil.copyProperties(request,entity);
		TDatabaseInfoService.checkDatabaseConnect(entity);
		return ApiResponse.ok();
	}


	@RequestMapping(value = "/queryDatasource", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@ApiOperation(value = "查询各数据源中的表（树形结构）", notes = "查询各数据源中的表（树形结构）")
	public ApiListResponse queryDatasource(@RequestParam(name = "tableName",required = false) String  tableName) {
		return ApiListResponse.ok(TDatabaseInfoService.getDatasourcesGroupByDatabaseType(tableName));
	}


	@RequestMapping(value = "/queryDatasourceTables", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@ApiOperation(value = "查询各数据源中表的列信息（树形结构）", notes = "查询各数据源中表的列信息（树形结构）")
	public ApiListResponse queryDatasourceAllTables(@RequestParam(name = "tableName",required = false) String  tableName) {
		return ApiListResponse.ok(TDatabaseInfoService.getDatasourcesAllTableInfo(tableName));
	}



	@RequestMapping(value = "/queryTableNamesByDatabaseId", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@ApiOperation(value = "查询库中的表名称-下拉列表", notes = "查询库中的表名称-下拉列表")
	public ApiListResponse<String> queryTableNamesByDatabaseId(@RequestParam(name = "databaseId") String  databaseId) {
		return ApiListResponse.ok(TDatabaseInfoService.getTablesNameByDatabaseId(databaseId));
	}


	@RequestMapping(value = "/queryTableInfo", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@ApiOperation(value = "查询库中的表列表信息", notes = "查询库中的表列表信息")
	public ApiListResponse<Map<String,Object>> queryTableInfoByDatabaseId(@RequestParam @ApiParam(required = true, name = "databaseId", value = "数据库ID") String  databaseId,
																		  @RequestParam(name = "tableName",required = false) String  tableName) {
		return ApiListResponse.ok(TDatabaseInfoService.getTableInfoByDatabaseId(databaseId,tableName));
	}



	@RequestMapping(value = "/queryTablesColumns", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@ApiOperation(value = "查询表的列和索引", notes = "查询表的列和索引")
	public ApiListResponse queryTablesColumns(@RequestParam @ApiParam(required = true, name = "type", value = "字段_colunm,索引_index") String  type,
														  @RequestParam(name = "databaseId") String  databaseId,
														  @RequestParam(name = "tableName") String  tableName) {
		if("colunm".equalsIgnoreCase(type)){
			return ApiListResponse.ok(TDatabaseInfoService.getTablesColumns(databaseId,tableName));
		}else if("index".equalsIgnoreCase(type)){
			return ApiListResponse.ok(TDatabaseInfoService.getTablesIndexs(databaseId,tableName));
		}
		return ApiListResponse.error("500","type参数不对");

	}
	@RequestMapping(value = "/queryTablesIncreColumns", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@ApiOperation(value = "查询表的自增列", notes = "查询表的自增列")
	public ApiListResponse queryTablesIncreColumns(@RequestParam(name = "databaseId") String  databaseId,
												   @RequestParam(name = "tableName") String  tableName) {
		return ApiListResponse.ok(TDatabaseInfoService.getTablesIncreColumns(databaseId,tableName));

	}

	@RequestMapping(value = "/updateTableComment", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@ApiOperation(value = "修改表注释", notes = "修改表注释")
	public ApiResponse updateTableComment(@RequestParam @ApiParam(name = "databaseId",required = true, value = "数据库ID") String  databaseId,
										  @RequestParam @ApiParam(name = "tableName",required = true ,value = "表名") String  tableName,
										  @RequestParam @ApiParam(name = "comment",required = true ,value = "注释") String  comment) {
		return TDatabaseInfoService.updateTableComment(databaseId,tableName,comment);
	}



}
